package com.nikmesoft.android.ebox.activities;

import java.io.File;
import java.io.IOException;
import com.nikmesoft.android.ebox.R;
import com.nikmesoft.android.ebox.helpers.FileHelper;
import com.nikmesoft.android.ebox.models.Item.Type;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;

public class PlayVideosActivity extends Activity {

	private File vidFile;
	private String path_video;
	private String name;
	private String currentPath;
	private VideoView myVideo;
	private ProgressDialog progressDialog;
	private VideoView videoPlayer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_play_videos);
		myVideo = (VideoView) findViewById(R.id.videoPlayName);
		registerForContextMenu(myVideo);

		name = getIntent().getStringExtra("KEY");

		path_video = getIntent().getStringExtra("PATH")
				+ getIntent().getStringExtra("KEY");
		videoPlayer = (VideoView) findViewById(R.id.videoPlayName);

		currentPath = getIntent().getStringExtra("Currentpath");

		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Decoding your video...");
		MediaController mc = new MediaController(this);
		videoPlayer.setMediaController(mc);
		new DecryptTask().execute();
	}

	private class DecryptTask extends AsyncTask<Void, Void, String> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressDialog.show();
		}

		@Override
		protected String doInBackground(Void... params) {
			// decode
			File sourceLocation = new File(FileHelper.getInstance()
					.getFullPath(path_video, Type.Video));
			vidFile = new File(FileHelper.getInstance().getFullPath(
					path_video + "e", Type.Video));

			try {
				FileHelper.getInstance().decode(sourceLocation, vidFile);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return vidFile.getAbsolutePath();
		}

		@Override
		protected void onPostExecute(String result) {
			if (result != null) {
				videoPlayer.setVideoPath(result);
				videoPlayer.start();
			}
			progressDialog.dismiss();
		}

	};

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_videos, menu);
		return true;
	}

	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Task");
		menu.add(0, v.getId(), 0, getString(R.string.contextmenu_item_rename));
		menu.add(1, v.getId(), 0,
				getString(R.string.contextmenu_item_back2galley));
	}

	public boolean onContextItemSelected(MenuItem item) {

		if (item.getTitle().equals(getString(R.string.contextmenu_item_rename))) {
			createRenameDialog(item.getItemId());

		} else if (item.getTitle().equals(
				getString(R.string.contextmenu_item_back2galley))) {
			saveTogallery();
			Toast.makeText(PlayVideosActivity.this, "Video's saved back...!",
					Toast.LENGTH_SHORT).show();
		} else {
			return false;
		}
		return true;
	}

	public void confirmDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Delete");
		alert.setMessage("Are you sure ?");

		// Set an EditText view to get user input

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				vidFile.delete();
				finishActivity(RESULT_OK);

			}
		});
		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();

	}

	public void createRenameDialog(int id) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Rename");
		alert.setMessage("Enter new name");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		input.setHint(nameToHint());
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				String ext;
				String newname = input.getText().toString().trim();
				if (newname.equals("")) {
					Toast.makeText(PlayVideosActivity.this, "Name is empty",
							Toast.LENGTH_SHORT).show();
				} else {
					File dir = new File(currentPath);
					ext = "."
							+ name.substring((name.lastIndexOf(".") + 1),
									name.length());
					if (ext.equals("." + name)) {
						ext = "";
					}

					if (dir.exists()) {
						File from = new File(dir, name);
						File to = new File(dir, newname + ext);
						if (to.exists()) {
							Toast.makeText(PlayVideosActivity.this,
									"Name is exist!", Toast.LENGTH_SHORT)
									.show();
						} else {
							from.renameTo(to);
							Toast.makeText(PlayVideosActivity.this,
									"Rename complete..!", Toast.LENGTH_SHORT)
									.show();
						}
					}
					setResult(RESULT_OK);
					finish();

				}
			}
		});
		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();

	}

	public String nameToHint() {
		String test = name;
		String ext;
		ext = "." + name.substring((name.lastIndexOf(".") + 1), name.length());
		return test.substring(0, test.length() - ext.length());
	}

	public void saveTogallery() {
		String file_path = currentPath + name;
		File sourceFile = new File(file_path);
		File desFile = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/DCIM/" + name);
		if (!desFile.exists()) {
			try {
				desFile.createNewFile();
				VideosActivity.copyDirectory(sourceFile, desFile);
				sourceFile.delete();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.share_videos:
			Intent shareIntent = new Intent(Intent.ACTION_SEND);
			Uri videotUri = Uri.parse(path_video);
			shareIntent.setData(videotUri);
			shareIntent.setType("video/*");
			shareIntent.putExtra(Intent.EXTRA_STREAM, videotUri);
			startActivity(Intent.createChooser(shareIntent, "Share Via"));
			break;
		case R.id.delete_videos:
			confirmDialog();
			break;
		case R.id.task_videos:
			openContextMenu(myVideo);
			break;
		}
		return true;
	}

	@Override
	protected void onDestroy() {
		if (vidFile != null) {
			vidFile.delete();
			vidFile = null;
		}
		super.onDestroy();
	}

	@Override
	protected void onStop() {
		if (vidFile != null) {
			vidFile.delete();
			vidFile = null;
		}
		super.onStop();
	}

}
